import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { RestaurantEntity } from '@/entity/restaurant.entity';
import { CreateRestaurantDto } from '@/modules/restaurant/dto/create-restaurant.dto';
import { UpdateRestaurantDto } from '@/modules/restaurant/dto/update-restaurant.dto';

@Injectable()
export class RestaurantService {
  constructor(
    @InjectRepository(RestaurantEntity)
    private RestaurantEntityRepository: Repository<RestaurantEntity>,
  ) {}

  async findAll(): Promise<RestaurantEntity[]> {
    return this.RestaurantEntityRepository.find();
  }

  async findOne(id: number): Promise<RestaurantEntity> {
    const RestaurantEntity = await this.RestaurantEntityRepository.findOne({
      where: { id },
    });
    if (!RestaurantEntity) {
      throw new NotFoundException('未找到该餐厅');
    }
    return RestaurantEntity;
  }

  async create(
    createRestaurantDto: CreateRestaurantDto,
  ): Promise<RestaurantEntity> {
    const restaurant = new RestaurantEntity();
    restaurant.name = createRestaurantDto.name;
    restaurant.address = createRestaurantDto.address;
    restaurant.longitude = createRestaurantDto.longitude;
    restaurant.latitude = createRestaurantDto.latitude;
    restaurant.image = createRestaurantDto.image;
    restaurant.notice = createRestaurantDto.notice;
    restaurant.phone = createRestaurantDto.phone;
    restaurant.minPrice = createRestaurantDto.minPrice;
    restaurant.deliveryFee = createRestaurantDto.deliveryFee;
    return this.RestaurantEntityRepository.save(restaurant);
  }

  async delete(id: number): Promise<void> {
    const RestaurantEntity = await this.findOne(id);
    await this.RestaurantEntityRepository.remove(RestaurantEntity);
  }

  async update(
    id: number,
    updateRestaurantDto: UpdateRestaurantDto,
  ): Promise<RestaurantEntity> {
    const found = await this.findOne(id);
    const updated = Object.assign(found, updateRestaurantDto);
    return this.RestaurantEntityRepository.save(updated);
  }
}
